<?php


namespace App\Http\Controllers\Saas;


use App\Http\Resources\PaginationCollection;
use App\Model\Bill;
use App\Utils\Result;
use Illuminate\Http\Request;

class BillController
{
    public function index(Request $request)
    {
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $keyword = $request->input('keyword');
        $type = $request->input('type');
        $payment = $request->input('payment');
        $start = $request->input('start');
        $end = $request->input('end');
        $query = Bill::query();
        $query->when($keyword, function($q) use ($keyword) {
            $q->where('order_no', $keyword);
        });
        if ($type) {
            $query->where('type', $type);
        }
        if($start){
            $query->where('created_at','>=',$start.' 00:00:00');
        }
        if($end){
            $query->where('created_at','<=',$end.' 23:59:59');
        }
        $query->with(['house', 'user', 'business', 'business.user', 'billPay', 'device']);
        $data = $query->where('is_close', 0)->where('is_paid', 1)
            ->whereHas('billPay', function ($query) use ($payment) {
                if($payment != ''){
                    $query->where('payment',$payment);
                }
            })
            ->orderByDesc('paid_at')
            ->paginate($perPage, ['*'], 'page', $page);

        return Result::success(new PaginationCollection($data));
    }
}
